package com.dart.sys.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dart.commons.base.web.BaseController;
import com.dart.framework.common.kaptcha.impl.DefaultKaptcha;

@Controller
public class KaptchaController extends BaseController {

	@Autowired
	private DefaultKaptcha kaptcha;
	
	@RequestMapping(value = "/kaptcha")
	public void kaptcha() {
		ServletOutputStream out = null ;
		try {
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			response.setHeader("Pragma", "no-cache");
			response.setContentType("image/jpeg");
			String capText = kaptcha.createText();
			request.getSession().setAttribute(com.dart.framework.common.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
			BufferedImage bi = kaptcha.createImage(capText);
			out = response.getOutputStream();
			ImageIO.write(bi, "jpg", out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != out) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
